package com.hengpeng.common.config.monitor;

import java.io.File;
import java.util.Observable;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

/**
 * <pre>
 * 文件监听实现
 * </pre>
 * @author chenjian
 * @version 1.0, 2010-12-24
 */
public class FileMonitorObserver<T> extends Observable
{
	private Timer timer = null;

	private FileListener<T> fileListener = null;

	private String filePath;

	public static Logger logger = Logger.getLogger(FileMonitorObserver.class);

	public FileMonitorObserver(String path, FileListener<T> fileListener)
	{
		super();
		this.filePath = path;
		this.fileListener = fileListener;
		init();
	}

	private void init()
	{
		this.addObserver(fileListener.getObserver());

	}

	public void start(long checkTime)
	{
		if (timer == null)
		{
			logger.info("开始监听配置文件{" + filePath + "}");
			timer = new Timer(true);
			timer.schedule(new FileMonitorTask(filePath), checkTime, checkTime);
		}
	}

	public void end()
	{
		if (timer != null)
		{
			logger.info("取消监听配置文件{" + filePath + "}");
			timer.cancel();
			timer = null;
		}
	}

	/**
	 * <pre>
	 * 用于检查文件变化的定时器
	 * </pre>
	 * @author chenjian
	 * @version 1.0, 2010-12-22
	 */
	private class FileMonitorTask extends TimerTask
	{
		private String path;

		private File file;

		private long lastModified;

		public FileMonitorTask(String path)
		{
			this.path = path;
			this.file = new File(this.path);
			this.lastModified = this.file.lastModified();
		}

		public void run()
		{
			long latestChange = file.lastModified();
			if (latestChange != lastModified)
			{
				logger.info("检测到配置文件{" + path + "}发生变化, 系统发送通知给观察者");
				lastModified = latestChange;
				FileMonitorObserver.this.end();
				// 如果检查到文件变化，则向观察着发送通知
				FileMonitorObserver.this.setChanged();
				FileMonitorObserver.this.notifyObservers(fileListener.getConfigProvider());
			}
		}
	}
}
